﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Slaks.Graphs.Analysis.ClusteringMeasures
{
    public class RandIndex : ClusteringMeasureBase
    {
        public override object evaluate(GraphList[] clusters, Slaks.Graphs.Category.CategoriesFile categoriesFile)
        {
            double randIndex = 0.0;

            long agreement = 0;
            long disagreement = 0;

            Graph graph1, graph2;
            string category1, category2;
            

            //AddCentroidsToList(clusters);

            //iterate through clusters
            for (int i = 0; i < clusters.Length; i++)
            {
                //start with the first cluster (i) and increase
                for (int j = 0; j < clusters[i].Count; j++)
                {
                    graph1 = clusters[i][j]; //take graph from cluster i at position j

                    for (int m = i; m < clusters.Length; m++)
                    {
                        //if the i cluster equals m cluster then start from the next graph, otherwise start from the first graph
                        for (int k = ((m == i) ? (j + 1) : 0); k < clusters[m].Count; k++)
                        {
                            graph2 = clusters[m][k]; //take graph from cluster m at position k

                            category1 = ((categoriesFile.DocumentToCategoryMap == null) ? graph1.Category : categoriesFile.DocumentToCategoryMap[graph1.Name]);
                            category2 = ((categoriesFile.DocumentToCategoryMap == null) ? graph2.Category : categoriesFile.DocumentToCategoryMap[graph2.Name]);

                            if (category1 == category2 && i == m)
                            {
                                ++agreement;
                            }
                            else if (category1 != category2 && i != m)
                            {
                                ++agreement;
                            }
                            else ++disagreement;
                        }
                    }
                }
            }
            randIndex = (double)agreement / (agreement + disagreement);

            //RemoveCentroidsFromList(clusters);

            return randIndex;
        }


        public override string getMeasureName()
        {
            return "RandIndex";
        }
    }
}
